<template>
    <view>
        <u-navbar :title="curChat.name" :autoBack="true" :placeholder="true">
        </u-navbar>
        <view class="main">
            <scroll-view class="chatMsgList" scroll-y="true" :style="'height: ' + screenHeight + 'px;'"
                :scroll-top="topHeight">
                <view :id="'msg' + index" class="msgItem" v-for="item, index in curChat.messageList" :key="index">
                    <view v-show="item.type == 'my'"
                        :class="{ myMsg: item.type == 'my', Rotate1: showPhoto == true, Rotate2: showPhoto == false }">
                        <view v-if="item.content.includes('3066/Files')">
                            <image @click="preview(item.content)" style="width:10rem;border-radius: 1rem;"
                                shape="square" mode="aspectFill" radius="2rem" :src="item.content">
                            </image>
                        </view>
                        <view v-else class="msg"
                            :style="'background:' + (curIndex == index ? '#EBF4FF' : '#d2e6fe') + ';'"
                            @touchstart="pressed(index)" @touchmove="bounce(index)" @touchend="bounce(index)"
                            @longpress="longPress(item.content)">
                            {{ item.content, }}</view>
                        <u-avatar class="avatar" :src="curChat.avatar"></u-avatar>
                    </view>

                    <view v-show="item.type == 'other'" :class="{ otherMsg: item.type == 'other' }">
                        <u-avatar class="avatar" :src="curChat.avatar"></u-avatar>
                        <view v-if="item.content.includes('3066/Files')">
                            <image shape="square" @click="preview(item.content)"
                                style="width:10rem;border-radius: 1rem;" mode="aspectFill" radius="2rem"
                                :src="item.content">
                            </image>
                        </view>
                        <view v-else class="msg"
                            :style="'background:' + (curIndex == index ? '#f5f5f5' : 'white') + ';'"
                            @touchstart="pressed(index)" @touchmove="bounce(index)" @touchend="bounce(index)"
                            @longpress="longPress(item.content)">
                            {{ item.content }}</view>
                    </view>
                </view>
            </scroll-view>
            <!-- 等高TabBar的填充区域 -->
            <view class="divider" :style="'height:' + safeBottom + 'rem'"></view>
            <view class="bottomFunc">
                <view class="inputBtn">
                    <i class=" iconfont icon-yuyin" @click="voice"></i>
                    <u-input class="input" @focus="inputFocus" v-model="value"></u-input>
                    <i class=" iconfont icon-emoji" @click="showEmojiFun"></i>
                    <u-button v-show="value != ''" class="btn" type="primary" @click="sendMsg">发送</u-button>
                    <i v-show="value == ''" class="addIcon iconfont icon-roundadd"
                        :class="{ Rotate2: showPhoto == true, Rotate1: showPhoto == false && isNotInput == false }"
                        @click="showPhotoFun"></i>
                </view>
                <view v-show="showPhoto" class="photoFunc">
                    <view class="album" @click="photo">
                        <i class=" iconfont icon-photo"></i>
                        <span>相册</span>
                    </view>
                    <view class="picture" @click="picture">
                        <i class=" iconfont icon-photo1"></i>
                        <span>拍照</span>
                    </view>
                </view>
                <view v-show="showEmoji" class="emoji">
                    <emojiView @setEmoji="addEmoji" :emojiList="emojiList">
                        <template>
                            <view class="deleteIcon" v-show="value !== ''" @click="deleteValue">
                                <i class=" iconfont icon-delete"></i>
                            </view>
                        </template>
                    </emojiView>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapGetters } from 'vuex'
import emojiView from './emoji'
import emoji from '@/utils/emoji.js'
import { uploadBookCover } from '@/Api'
export default {

    mounted() {
        this.emojiList = emoji
        this.screenHeight = this.$tools.getScreenHeight() - 6 * 16 - 3.8 * 16
        this.lastChild = "#msg" + (this.curChat.messageList.length - 1)
        this.getChatListHeight()
    },
    components: {
        emojiView,
    },
    computed: {
        ...mapGetters(['curChat', 'userInfo', 'otherInfo']),
    },
    data() {
        return {
            topHeight: 1000,
            value: '',//输入框的值
            showPhoto: false,//显示相册相机功能区
            showEmoji: false,//显示表情区
            isNotInput: true,//是否由输入框获取焦点触发
            emojiList: [],//表情列表
            safeBottom: 5,//底部安全距离
            curIndex: -1,//当前选中的对话框
            chatListHeight: 0,//聊天列表高度
            screenHeight: 0,//屏幕高度
            lastChild: "",
        }
    },
    methods: {
        preview(url) {
            uni.previewImage({
                // 预览图片  图片路径必须是一个数组 => ["http://192.168.100.251:8970/6_1597822634094.png"]
                current: 0,
                urls: [url],
                longPressActions: {
                    //长按保存图片到相册
                    itemList: ["保存图片"],
                    success: (data) => {
                        //将图片保存到相册
                        uni.saveImageToPhotosAlbum({
                            filePath: url,
                            success: (res) => {
                                console.log(res);
                                this.$tools.toast('保存成功')
                            },
                            fail: (err) => {
                                console.log(err);
                                this.$tools.toast('保存失败')

                            },
                        });
                    },
                    fail: (err) => {
                        console.log(err.errMsg);
                    },
                },
            });
        },
        // 监听软键盘的高度

        // 获取聊天列表的高度
        getChatListHeight() {
            let query = uni.createSelectorQuery().in(this);
            query.select(this.lastChild).boundingClientRect(data => {
                this.chatListHeight = data.top + 50000
                // console.log('chatListHeight', this.chatListHeight)
            }).exec();
        },

        photo() {
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album'],
                success: (res) => {
                    uploadBookCover(res.tempFilePaths[0]).then(ret => {
                        let data = JSON.parse(ret.data)
                        if (data.status == 200) {
                            let data = JSON.parse(ret.data)
                            this.value = data.data
                            this.sendMsg()
                        } else {
                            this.$tools.toast('上传失败')
                        }
                    })
                    // this.sendMsg(res.tempFilePaths[0])
                }
            });
        },
        picture() {
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['camera'],
                success: (res) => {
                    uploadBookCover(res.tempFilePaths[0]).then(ret => {
                        let data = JSON.parse(ret.data)
                        this.value = data.data
                        this.sendMsg()
                    })
                    // this.sendMsg(res.tempFilePaths[0])
                }
            });
        },
        // 长按事件
        longPress(msg) {
            // 复制到剪切板
            if (this.curIndex != -1)
                uni.setClipboardData({
                    data: msg,
                    success: res => {
                        this.$tools.toast('已复制到剪切板')
                        this.bounce()//抬起手指
                    }
                })
        },
        pressed(index) {
            this.curIndex = index
        },
        bounce() {
            this.curIndex = -1  //复位当前的选中索引
        },
        // 判断是否是表情
        isEmoji(str) {
            // 将所有表情转换成unicode编码
            let reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
            return reg.test(str)
        },

        deleteValue() {
            // 将字符串最后一个字符删除，如果是表情，则删除最后一个表情
            let value = this.value
            let last = value.substring(value.length - 2, value.length)
            if (this.isEmoji(last)) {
                this.value = value.slice(0, value.length - 2)
            } else {
                this.value = value.slice(0, value.length - 1)
            }
        },
        // 添加表情
        addEmoji(item, index) {
            this.value += item
        },
        //整合消息，使用sokect发送到服务器
        submitMsgToSoket() {
            let data = {
                type: 'my',
                senderId: this.userInfo.id,
                senderName: this.userInfo.nickName || this.userInfo.email,
                senderAvatar: this.userInfo.avatar || 'http://182.61.31.180:5000/images/1653403893152_logo.png',//如果没有头像，则使用默认头像
                receiverId: this.otherInfo.id,
                receiverName: this.otherInfo.nickName || this.otherInfo.email,
                receiverAvatar: this.otherInfo.avatar || 'http://182.61.31.180:5000/images/1653403893152_logo.png',//如果没有头像，则使用默认头像
                content: this.value,
            }
            console.log('data', data)
            this.$socket.emit('privateChat', data)
        },
        // 发送消息
        sendMsg() {
            let data = {
                type: 'my',
                content: this.value,
                from: this.curChat.id,
                to: this.curChat.id,
                time: new Date().getTime()
            }
            if (this.value != '') {
                //如果消息不为空，将消息清空，提交到vuex中，并发送给服务器
                this.$store.dispatch('sendMsg', data)
                this.submitMsgToSoket()
                this.$nextTick(() => {
                    this.topHeight += 100
                    this.lastChild = "#msg" + (this.curChat.messageList.length - 1)
                    this.getChatListHeight()
                })
                this.value = ''
            }
        },
        // 更改底部安全距离
        changeSafeBottom() {
            this.safeBottom = 5
            if (this.showPhoto)
                this.safeBottom += 4
            else if (this.showEmoji)
                this.safeBottom += 15
        },
        // 输入框获取焦点
        inputFocus() {
            this.isNotInput = true
            this.showPhoto = false
            this.showEmoji = false
            this.changeSafeBottom()
            this.getChatListHeight()
        },
        // 显示相机面板
        showPhotoFun() {
            this.isNotInput = false
            this.showEmoji = false
            this.showPhoto = !this.showPhoto
            this.changeSafeBottom()
            this.getChatListHeight()
            setTimeout(() => {
                this.isNotInput = true
            }, 1000)
        },
        // 显示表情面板
        showEmojiFun() {
            this.isNotInput = false
            this.showPhoto = false
            this.showEmoji = !this.showEmoji
            this.changeSafeBottom()
            this.getChatListHeight()
            setTimeout(() => {
                this.isNotInput = true
            }, 1000)
        },
        voice() {
            this.$tools.toast('语音功能暂未开放')
        }
    }
}
</script>

<style lang="scss">
page {
    height: 100%;
    width: 100%;

    .main {
        width: 100%;

        .chatMsgList {
            width: 100%;

            .msgItem {
                width: 100%;
                padding: 1rem 0;

                .myMsg {
                    width: 100%;
                    display: flex;
                    justify-content: right;
                    height: 100%;

                    .msg {
                        margin-top: 0.5rem;
                        margin-right: 0.5rem;
                        background: white;
                        max-width: 15rem;
                        border-radius: 0.4rem;
                        padding: 0.5rem;
                        // overflow: auto;
                        border-top-right-radius: 0;

                        // 文字溢出省略号
                        // text-overflow: ellipsis;
                        // white-space: nowrap;
                        word-break: break-all;

                    }

                    .avatar {
                        margin-right: 0.5rem;
                    }
                }

                .otherMsg {
                    width: 100%;
                    display: flex;
                    justify-content: left;
                    height: 100%;


                    .msg {
                        margin-top: 0.5rem;
                        margin-left: 0.5rem;
                        background: #f5f5f5;
                        max-width: 15rem;

                        border-radius: 0.4rem;
                        border-top-left-radius: 0;
                        padding: 0.5rem;
                        // overflow: auto;
                        // 文字溢出省略号
                        // text-overflow: ellipsis;
                        // white-space: nowrap;
                        word-break: break-all;
                    }

                    .avatar {
                        margin-left: 0.5rem;
                    }
                }

            }

        }

        .divider {
            width: 100%;
        }

        .bottomFunc {

            position: fixed;
            bottom: 0;
            width: 100%;
            // height: 4rem;
            background: white;


            .inputBtn {
                width: 100%;
                height: 4rem;
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                align-items: center;
                padding: 0.5rem;

                @keyframes rot2 {
                    from {
                        transform: rotate(0deg);
                    }

                    to {
                        transform: rotate(45deg);
                        // transition: all 0.2s;
                    }

                }

                @keyframes rot1 {
                    from {
                        transform: rotate(45deg);
                    }

                    to {
                        transform: rotate(0deg);
                        // transition: all 0.2s;

                    }

                }

                .Rotate1 {
                    animation: rot1 0.5s;

                }

                .Rotate2 {

                    animation: rot2 0.5s;
                    transform: rotate(45deg);

                }

                .icon-yuyin {
                    font-size: 2rem;
                    color: #999;

                }

                .input {
                    width: 80%;
                    height: 1.8rem;
                    border-radius: 0.5rem;
                    border: 1px solid #e5e5e5;
                }

                .btn {
                    width: 4rem;
                    margin: 0 1rem 0 0.3rem;
                    border-radius: 0.5rem;
                }

                .icon-emoji {
                    font-size: 2rem;
                    color: #999;
                    margin-left: 0.3rem;
                    // margin: 0 0 0 0.5rem;
                }



                .addIcon {
                    margin: 0 1rem 0 0;
                    font-size: 2rem;
                    color: #999;

                    // margin: 0 0 0 0.5rem;
                }


            }

            .photoFunc {
                margin-left: 1rem;
                display: flex;
                flex-direction: row;
                justify-content: left;
                align-items: center;
                padding: 0.5rem;
                height: 3rem;

                .album,
                .picture {
                    display: flex;
                    flex-direction: column;
                    margin-left: 1rem;
                    justify-content: center;
                    align-items: center;

                    i {
                        font-size: 2rem;
                        color: #999;
                    }

                    span {
                        font-size: 0.6rem;
                        color: #999;
                    }
                }

            }

            .emoji {
                height: 15rem;
                overflow: auto;

                .deleteIcon {
                    background: white;
                    width: 3rem;
                    position: absolute;
                    top: 16rem;
                    right: 2rem;
                    box-shadow: 0 0 0 1px #e5e5e5;
                    text-align: center;
                    border-radius: 0.3rem;
                    height: 2rem;
                    display: flex;
                    justify-content: center;
                    align-items: center;

                    .icon-delete {
                        font-size: 1.5rem;
                        color: #999;
                    }
                }
            }
        }
    }
}
</style>